package com.rongxunwu.netty.hello;

import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;



import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;

/**
 * TODO
 *
 * @author rongxun.wu01
 * @version 1.0
 * @date 2021/10/29 8:51
 */

public class ServerStarter {

    private EventLoopGroup boss ;

    private EventLoopGroup worker ;

    private int port;

    private static int DEFAULT_PORT = 8080;

    public ServerStarter() throws InterruptedException {
        boss = new NioEventLoopGroup();
        worker = new NioEventLoopGroup();
        port = DEFAULT_PORT;
        this.startup();
    }

    public ServerStarter(int port) throws InterruptedException {
        this();
        if(port < 0 || port > 65535){
            throw new IllegalArgumentException("port:"+port+" is illegal");
        }
        this.port = port;
        this.startup();
    }

    public void startup() throws InterruptedException{

        if(boss.isShutdown() || worker.isShutdown()){
            throw new IllegalStateException("server was closed");
        }
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        System.out.println("=====http server start ");
        serverBootstrap.channel(NioServerSocketChannel.class)
                .group(boss,worker)
                .childOption(ChannelOption.SO_KEEPALIVE,true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new HttpServerHandler());
                    }
                })
                .option(ChannelOption.SO_BACKLOG,1024)//设置TCP缓冲区
                .option(ChannelOption.SO_SNDBUF,32*1024)//设置发送缓冲区大小
                .option(ChannelOption.SO_RCVBUF,32*1024)//设置接收缓冲区大小

                .option(ChannelOption.SO_KEEPALIVE,true);//保持连接

        ChannelFuture future = serverBootstrap.bind(port).sync();
        System.out.println("server port listen："+port);
        future.channel().closeFuture().sync();
        shutDownGracefully();
    }

    /**
     * 关闭管道
     */
    public void shutDownGracefully(){
        this.boss.shutdownGracefully();
        this.worker.shutdownGracefully();
    }

    public static void main(String[] args) throws InterruptedException {
        new ServerStarter(8080);
    }
}
